package com.lxd.sunso.product.service.impl;

import com.lxd.sunso.common.utils.DateUnit;
import com.lxd.sunso.common.utils.PageUtils;
import com.lxd.sunso.common.utils.Query;
import com.lxd.sunso.product.components.AliSendEmailUtil;
import com.lxd.sunso.product.components.SmsComponent;
import com.lxd.sunso.product.entity.*;
import com.lxd.sunso.product.service.*;
import com.lxd.sunso.product.vo.MessageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxd.sunso.product.dao.AlarmregisterDao;


@Service("alarmregisterService")
public class AlarmregisterServiceImpl extends ServiceImpl<AlarmregisterDao, AlarmregisterEntity> implements AlarmregisterService {

    @Autowired
    private UserService userService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private DatatemplateService datatemplateService;

    @Autowired
    private MachineService machineService;

    @Autowired
    private ControlrealtimeService controlrealtimeService;

    @Autowired
    private MachinekindService machinekindService;

    @Autowired
    private AlarmhisdataService alarmhisdataService;

    @Autowired
    SmsComponent smsComponent;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String userName = (String) params.get("userName");
        UserEntity userEntity = userService.getOne(new QueryWrapper<UserEntity>().eq("UserName", userName));
        CustomerEntity customerEntity = customerService.getById(userEntity.getUserid());
        IPage<AlarmregisterEntity> page = this.page(
                new Query<AlarmregisterEntity>().getPage(params),
                new QueryWrapper<AlarmregisterEntity>().eq("CustomerID", customerEntity.getId())
        );

        List<AlarmregisterEntity> entities = page.getRecords();
        List<AlarmregisterEntity> list = addMessage(entities);
        page.setRecords(list);
        return new PageUtils(page);
    }


    @Override
    public PageUtils search(String machineName, Map<String, Object> params) {
        MachineEntity machineEntity = machineService.getOne(new QueryWrapper<MachineEntity>().eq("MachineName", machineName));
        IPage<AlarmregisterEntity> page = this.page(
                new Query<AlarmregisterEntity>().getPage(params),
                new QueryWrapper<AlarmregisterEntity>().eq("MachineId", machineEntity.getId())
        );

        List<AlarmregisterEntity> entities = page.getRecords();
        List<AlarmregisterEntity> list = addMessage(entities);
        page.setRecords(list);

        return new PageUtils(page);
    }

    @Override
    public void newsave(AlarmregisterEntity alarmregister) {
        alarmregister.setCreatetime(DateUnit.dateFormat(new Date()));
        String datatemplateId = alarmregister.getControllername();
        //DatatemplateEntity datatemplateEntity = datatemplateService.getOne(new QueryWrapper<DatatemplateEntity>().eq("ControlName", controllername));
        alarmregister.setDatatemplateid(Long.valueOf(datatemplateId));
        String machinename = alarmregister.getMachinename();
        MachineEntity machineEntity = machineService.getOne(new QueryWrapper<MachineEntity>().eq("MachineName", machinename));
        alarmregister.setMachineid(machineEntity.getId());
        alarmregister.setCustomerid(machineEntity.getCustomerid());
        alarmregister.setIsonwarning("0");
        this.save(alarmregister);
    }

    @Override
    public AlarmregisterEntity findById(Long id) {
        AlarmregisterEntity entity = this.getById(id);
        MachineEntity machineEntity = machineService.getById(entity.getMachineid());
        entity.setMachinename(machineEntity.getMachinename());
        DatatemplateEntity datatemplateEntity = datatemplateService.getById(entity.getDatatemplateid());
        entity.setUnit(datatemplateEntity.getUnitname());
        entity.setControllername(datatemplateEntity.getControlname());
        return entity;
    }

    @Override
    public List<MessageVo> getKindAlarm() {
        List<MachinekindEntity> list = machinekindService.list();
        List<MessageVo> collect = list.stream().map(entity -> {
            Long num = this.baseMapper.queryKindNum(entity.getMachinenumber());
            if (num == null) {
                num = 0L;
            }
            MessageVo messageVo = new MessageVo();
            messageVo.setName(entity.getMachinenumber());
            messageVo.setValue(num);
            return messageVo;
        }).sorted(new Comparator<MessageVo>() {
            @Override
            public int compare(MessageVo o1, MessageVo o2) {
                return (int) (o2.getValue() - o1.getValue());
            }
        }).collect(Collectors.toList());

        List<MessageVo> messageVos = new ArrayList<>();
        if (collect.size() > 7) {
            messageVos.addAll(collect.subList(0, 7));
        } else {
            messageVos.addAll(collect);
        }

        Long sum = 0L;
        for (int i = 7; i < collect.size(); i++) {
            System.out.println(collect.get(i));
            sum += collect.get(i).getValue();
        }
        MessageVo messageVo = new MessageVo();
        messageVo.setName("其他");
        messageVo.setValue(sum);
        if (messageVo.getValue() != 0) {
            messageVos.add(messageVo);
        }
        return messageVos;
    }

    //发送邮件
    @Override
    @Async
    public void sendEmail(String email, String content) {
        try {
            String message = "尊敬的三向物联网平台用户，您有新的设备报警信息待处理。" + content + "，请及时处理";
            AliSendEmailUtil.sendEmail(email, message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //发送短信
    @Override
    @Async
    public void sendMessage(String phone, String machineKind, String machineName, String machineId, String message) {
        try {
            smsComponent.sendSmsCode(phone, machineKind, machineName, machineId, message);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }

    @Override
    public void removeRegister(List<Long> asList) {
        for (Long registerId : asList) {
            AlarmregisterEntity entity = this.getById(registerId);
            alarmhisdataService.remove(new QueryWrapper<AlarmhisdataEntity>().eq("DataTemplateID",
                    entity.getDatatemplateid()).eq("MachineId", entity.getMachineid()));
        }
        this.removeByIds(asList);
    }

    /**
     * 添加信息
     *
     * @param entities
     * @return
     */
    private List<AlarmregisterEntity> addMessage(List<AlarmregisterEntity> entities) {
        List<AlarmregisterEntity> list = entities.stream().map(entity -> {
            MachineEntity machineEntity = machineService.getById(entity.getMachineid());
            entity.setMachinename(machineEntity.getMachinename());
            DatatemplateEntity datatemplateEntity = datatemplateService.getById(entity.getDatatemplateid());
            entity.setUnit(datatemplateEntity.getUnitname());
            entity.setControllername(datatemplateEntity.getControlname());
            return entity;
        }).collect(Collectors.toList());
        return list;
    }

}